// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package app

import (
	"appengine"
	"appengine/channel"
	"appengine/datastore"
	"bytes"
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"net/mail"
	"strconv"
)

type Endpoint struct {
}

var mainTemplate = template.Must(template.ParseFiles("template.html"))

func appHandler(f func(c appengine.Context, w http.ResponseWriter, r *http.Request) error) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c := appengine.NewContext(r)
		err := f(c, w, r)
		if err != nil {
			c.Errorf("%v", err.Error())
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}

func init() {
	http.HandleFunc("/_ah/mail/", appHandler(incomingMail))
	http.HandleFunc("/", appHandler(mainPage))
	http.HandleFunc("/_ah/channel/connected/", appHandler(channelConnected))
	http.HandleFunc("/_ah/channel/disconnected/", appHandler(channelDisconnected))
}

func mainPage(c appengine.Context, w http.ResponseWriter, r *http.Request) error {
	low, _, err := datastore.AllocateIDs(c, "endpoint", nil, 1)
	if err != nil {
		return err
	}
	token, err := channel.Create(c, strconv.FormatInt(low, 10))
	if err != nil {
		return err
	}
	err = mainTemplate.Execute(w, token)
	if err != nil {
		return err
	}
	return nil
}

func incomingMail(c appengine.Context, w http.ResponseWriter, r *http.Request) error {
	defer r.Body.Close()
	msg, err := mail.ReadMessage(r.Body)
	if err != nil {
		return err
	}
	c.Infof("Received mail: %v", msg)
	var body bytes.Buffer
	if _, err := body.ReadFrom(msg.Body); err != nil {
		return err
	}
	q := datastore.NewQuery("endpoint").KeysOnly()
	endpoints, err := q.GetAll(c, nil)
	if err != nil {
		return err
	}
	message, err := json.Marshal(map[string]string{
		"From":    msg.Header.Get("From"),
		"To":      msg.Header.Get("To"),
		"Subject": msg.Header.Get("Subject"),
		"Body":    fmt.Sprintf("<div>%s</div>", body.String()),
	})
	if err != nil {
		return err
	}
	errc := make(chan error)
	for _, e := range endpoints {
		go func(e *datastore.Key) {
			err := channel.Send(c, strconv.FormatInt(e.IntID(), 10), string(message))
			if err != nil {
				// Send failed. Delete the endpoint.
				if err := datastore.Delete(c, e); err != nil {
					c.Errorf("deleting endpoint: %v", err)
				}
			}
			errc <- err
		}(e)
	}
	for i := 0; i < len(endpoints); i++ {
		if err := <-errc; err != nil {
			c.Errorf("sending message: %v", err)
		}
	}
	return nil
}

func channelConnected(c appengine.Context, w http.ResponseWriter, r *http.Request) error {
	from, err := strconv.ParseInt(r.FormValue("from"), 10, 0)
	if err != nil {
		return err
	}
	c.Infof("channel connected: %v", r.Form)
	if _, err := datastore.Put(c, datastore.NewKey(c, "endpoint", "", from, nil), &Endpoint{}); err != nil {
		return err
	}
	return nil
}

func channelDisconnected(c appengine.Context, w http.ResponseWriter, r *http.Request) error {
	from, err := strconv.ParseInt(r.FormValue("from"), 10, 0)
	if err != nil {
		return err
	}
	c.Infof("channel disconnected: %v", r.Form)
	if err := datastore.Delete(c, datastore.NewKey(c, "endpoint", "", from, nil)); err != nil {
		return err
	}
	return nil
}
